package com.xxxx.myproject.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.xxxx.myproject.entity.Bo.LoginUserBo;
import com.xxxx.myproject.entity.LoginUser;
import com.xxxx.myproject.entity.R;
import com.xxxx.myproject.entity.User;
import com.xxxx.myproject.service.LoginService;
import com.xxxx.myproject.service.UserService;
import com.xxxx.myproject.utils.JwtUtil;
import com.xxxx.myproject.utils.RedisCache;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisCache redisCache;

    @Override
    public HashMap<Object,Object> login(LoginUserBo userBo) {

        System.out.println("新写的登录方法-------");

        //1.封装Authentication对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userBo.getUserName(), userBo.getPassword());
        //2.通过AuthenticationManager的authenticate方法来进行用户认证
        Authentication authenticated = authenticationManager.authenticate(authenticationToken);
        System.out.println("退出账号密码验证方法---");
        //3.在Authentication中获取用户信息
        LoginUser loginUser = (LoginUser) authenticated.getPrincipal();
        System.out.println("封装的loginUser " + loginUser);
        String userId = loginUser.getUser().getId().toString();
        //4.认证通过生成token
        String jwt = JwtUtil.createJWT(userId);
        //5.用户信息存入redis
        redisCache.setCacheObject("login:" + userId, loginUser);
        //6.把token返回给前端
        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.put("token", jwt);
        return hashMap;
    }

    @Override
    public void logout() {
        //获取SecurityContextHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        //删除redis中的用户信息
        redisCache.deleteObject("login:" + userId);
    }
}
